package javabase.concurrent;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionCommunication {
	
	static class Business {
		Lock lock = new ReentrantLock();
		private AtomicInteger count = new AtomicInteger(0);
		Condition condition = lock.newCondition();
		public void inc() {
			lock.lock();
			try {
				while(count.get() > 50) {
					try {
						condition.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("inc" + count.incrementAndGet());
				condition.signal();
			} finally {
				lock.unlock();
			}
		}
		
		public void desc() {
			lock.lock();
			try {
				System.out.println("desc" + count.decrementAndGet());
				if (count.get() < 0 ) {
					try {
						condition.await();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				condition.signal();
			} finally {
				lock.unlock();
			}
		}
		
	}
	
	
	public static void main(String[] args) {
		Business business = new Business();
		new Thread(() -> {
			while (true) {
				business.inc();
			}
		}).start();
		
		new Thread(() -> {
			while(true) {
				business.desc();
			}
		}).start();
		
	}
	
}
